package com.chen.lifepic.downloader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

import com.chen.lifepic.utils.Utils;

public class HttpDownloader {
	ITaskListener _listener = null;

	public HttpDownloader(ITaskListener lis) {
		_listener = lis;
	}

	public String downloadToBuff(String urlStr) {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
			buffer = new BufferedReader(new InputStreamReader(
				urlConn.getInputStream()));
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public boolean downloadFileToPath(String urlStr, String path) {
		Log.d("test", "download begain path = " + path);
		if (null == urlStr || null == path)
			return false;

		InputStream inputStream = null;
		OutputStream outputStream = null;
		File file = null;

		try {
			if (Utils.isFileExist(path))
				return true;
			else {
				inputStream = getInputStreamFromUrl(urlStr);
				Utils.createDirIfNotExist(DownloadManager.DOWNLOAD_PATH);
				file = Utils.createFileIfNotExist(path);
				outputStream = new FileOutputStream(file);
				long downloadProgress = 0;
				byte buffer[] = new byte[1024 * 4];
				while (true) {
					int currentProgress = inputStream.read(buffer);
					if (-1 == currentProgress)
						break;
					downloadProgress += currentProgress;
					Log.d("test", "progress = " + downloadProgress);
					if (null != _listener) {
						_listener.TaskProgress(downloadProgress);
					}

					outputStream.write(buffer, 0, currentProgress);
				}
				outputStream.flush();

				if (file == null)
					return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				outputStream.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}

		}
		return true;
	}

	public InputStream getInputStreamFromUrl(String urlStr)
			throws MalformedURLException, IOException {
		URL url = new URL(urlStr);
		HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlCon.getInputStream();
		return inputStream;

	}
}
